package com.example.flower_shop.service.impl;

import com.example.flower_shop.dto.order.CreateOrderRequest;
import com.example.flower_shop.entity.CustomerOrder;
import com.example.flower_shop.entity.OrderItem;
import com.example.flower_shop.entity.Product;
import com.example.flower_shop.entity.User;
import com.example.flower_shop.enums.OrderStatus;
import com.example.flower_shop.exception.BusinessException;
import com.example.flower_shop.exception.ResourceNotFoundException;
import com.example.flower_shop.repository.CustomerOrderRepository;
import com.example.flower_shop.repository.OrderItemRepository;
import com.example.flower_shop.repository.ProductRepository;
import com.example.flower_shop.repository.UserRepository;
import com.example.flower_shop.service.AdminService;
import com.example.flower_shop.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final CustomerOrderRepository orderRepository;
    private final OrderItemRepository orderItemRepository;
    private final ProductRepository productRepository;
    private final UserRepository userRepository;
    private final AdminService adminService;

    @Override
    @Transactional
    public CustomerOrder createCustomerOrder(Long userId, CreateOrderRequest request) {
        // 获取用户信息
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户", userId));

        // 创建订单
        CustomerOrder order = new CustomerOrder();
        order.setUser(user);
        order.setOrderNo(generateOrderNo());
        order.setReceiverName(request.getReceiverName());
        order.setReceiverPhone(request.getReceiverPhone());
        order.setReceiverAddress(request.getReceiverAddress());
        order.setStatus(OrderStatus.PENDING_PAYMENT.getCode());
        order.setCreateTime(LocalDateTime.now());

        // 计算订单总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<OrderItem> orderItems = new ArrayList<>();

        for (CreateOrderRequest.OrderItemRequest itemRequest : request.getItems()) {
            Product product = productRepository.findById(itemRequest.getProductId())
                    .orElseThrow(() -> new BusinessException("PRODUCT_NOT_FOUND", "商品不存在"));

            // 检查商品状态和库存
            if (product.getStatus() != 1) {
                throw new BusinessException("PRODUCT_UNAVAILABLE", "商品已下架");
            }
            if (product.getStock() < itemRequest.getQuantity()) {
                throw new BusinessException("INSUFFICIENT_STOCK", "商品库存不足");
            }

            // 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setCustomerOrder(order);
            orderItem.setProduct(product);
            orderItem.setProductName(product.getName());
            orderItem.setProductPrice(product.getPrice());
            orderItem.setQuantity(itemRequest.getQuantity());
            orderItem.setSubtotal(product.getPrice().multiply(new BigDecimal(itemRequest.getQuantity())));

            orderItems.add(orderItem);
            totalAmount = totalAmount.add(orderItem.getSubtotal());

            // 更新商品库存
            product.setStock(product.getStock() - itemRequest.getQuantity());
            productRepository.save(product);
        }

        order.setTotalAmount(totalAmount);

        // 先保存订单，以获取订单ID
        order = orderRepository.save(order);

        // 保存订单项
        orderItems = orderItemRepository.saveAll(orderItems);
        order.setOrderItems(orderItems);

        return order;
    }

    @Override
    public Page<CustomerOrder> getCustomerOrders(Long userId, Pageable pageable) {
        return orderRepository.findByUserIdAndNotDeleted(userId, pageable);
    }

    @Override
    public Page<CustomerOrder> getCustomerOrdersByStatus(Integer status, Pageable pageable) {
        return orderRepository.findByStatus(status, pageable);
    }

    // 新增用户特定状态订单查询方法，供删除功能使用
    public Page<CustomerOrder> getUserOrdersByStatus(Long userId, Integer status, Pageable pageable) {
        return orderRepository.findByUserIdAndStatusAndNotDeleted(userId, status, pageable);
    }

    @Override
    public CustomerOrder getCustomerOrderByOrderNo(String orderNo) {
        return orderRepository.findByOrderNoAndNotDeleted(orderNo)
                .orElseThrow(() -> new BusinessException("ORDER_NOT_FOUND", "订单不存在"));
    }

    @Override
    @Transactional
    public CustomerOrder payCustomerOrder(String orderNo) {
        CustomerOrder order = getCustomerOrderByOrderNo(orderNo);
        if (order.getStatus() != OrderStatus.PENDING_PAYMENT.getCode()) {
            throw new BusinessException("INVALID_ORDER_STATUS", "订单状态不正确");
        }
        order.setStatus(OrderStatus.PAID.getCode());
        order.setPayTime(LocalDateTime.now());

        // 更新商家收入
        adminService.updateIncome(order.getTotalAmount());

        return orderRepository.save(order);
    }

    @Override
    @Transactional
    public CustomerOrder cancelCustomerOrder(String orderNo) {
        CustomerOrder order = getCustomerOrderByOrderNo(orderNo);
        if (order.getStatus() != OrderStatus.PENDING_PAYMENT.getCode()) {
            throw new BusinessException("INVALID_ORDER_STATUS", "订单状态不正确");
        }
        order.setStatus(OrderStatus.CANCELLED.getCode());
        order.setCancelTime(LocalDateTime.now());

        // 恢复商品库存
        for (OrderItem item : order.getOrderItems()) {
            Product product = item.getProduct();
            product.setStock(product.getStock() + item.getQuantity());
            productRepository.save(product);
        }

        return orderRepository.save(order);
    }

    @Override
    @Transactional
    public CustomerOrder confirmCustomerOrder(String orderNo) {
        CustomerOrder order = getCustomerOrderByOrderNo(orderNo);
        if (order.getStatus() != OrderStatus.SHIPPED.getCode()) {
            throw new BusinessException("INVALID_ORDER_STATUS", "订单状态不正确");
        }
        order.setStatus(OrderStatus.COMPLETED.getCode());
        order.setCompleteTime(LocalDateTime.now());
        return orderRepository.save(order);
    }

    @Override
    public Page<CustomerOrder> getMerchantOrders(Long merchantId, Pageable pageable) {
        return orderRepository.findByMerchantId(merchantId, pageable);
    }

    @Override
    public Page<CustomerOrder> getMerchantOrdersByStatus(Long merchantId, Integer status, Pageable pageable) {
        return orderRepository.findByMerchantIdAndStatus(merchantId, status, pageable);
    }

    @Override
    public CustomerOrder getMerchantOrderByOrderNo(String orderNo) {
        return getCustomerOrderByOrderNo(orderNo);
    }

    @Override
    @Transactional
    public CustomerOrder updateMerchantOrderStatus(String orderNo, Integer status, String processingNotes) {
        CustomerOrder order = getCustomerOrderByOrderNo(orderNo);
        order.setStatus(status);
        order.setProcessingNotes(processingNotes);

        if (status == OrderStatus.SHIPPED.getCode()) {
            order.setShipTime(LocalDateTime.now());
            // 订单发货时更新商家收入
            adminService.updateIncome(order.getTotalAmount());
        }

        return orderRepository.save(order);
    }

    @Override
    public long count() {
        return orderRepository.count();
    }

    @Override
    @Transactional
    public void deleteCustomerOrder(String orderNo, Long userId) {
        CustomerOrder order = orderRepository.findByOrderNoAndNotDeleted(orderNo)
                .orElseThrow(() -> new BusinessException("ORDER_NOT_FOUND", "订单不存在"));

        // 验证是否是用户自己的订单
        if (!order.getUser().getId().equals(userId)) {
            throw new BusinessException("UNAUTHORIZED", "无权操作此订单");
        }

        // 只允许删除已完成或已取消的订单
        if (order.getStatus() != OrderStatus.COMPLETED.getCode() &&
                order.getStatus() != OrderStatus.CANCELLED.getCode()) {
            throw new BusinessException("INVALID_ORDER_STATUS", "只能删除已完成或已取消的订单");
        }

        // 标记订单为已删除（软删除）
        order.setDeleted(true);
        orderRepository.save(order);
    }

    @Override
    @Transactional
    public void deleteMerchantOrder(String orderNo, Long merchantId) {
        CustomerOrder order = orderRepository.findByOrderNoAndNotDeleted(orderNo)
                .orElseThrow(() -> new BusinessException("ORDER_NOT_FOUND", "订单不存在"));

        // 只允许删除已完成或已取消的订单
        if (order.getStatus() != OrderStatus.COMPLETED.getCode() &&
                order.getStatus() != OrderStatus.CANCELLED.getCode()) {
            throw new BusinessException("INVALID_ORDER_STATUS", "只能删除已完成或已取消的订单");
        }

        // 标记订单为已删除（软删除）
        order.setDeleted(true);
        orderRepository.save(order);
    }

    private String generateOrderNo() {
        return LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                + UUID.randomUUID().toString().substring(0, 4);
    }
}